package designpattern.iterator;

import java.util.Iterator;
import java.util.List;

import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

class Iterators {
    public static <T> Stream<T> toStream(Iterator<T> iterator) {
        return StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED),
                false);
    }
}

public class Rotated {

    /**
     * Rotate the list by offset, return an Iterator
     */
    public static <A> Iterator<A> rotated(List<A> list, int offset) {
        return new Iterator<A>() {

            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < list.size();
            }

            @Override
            public A next() {
                A result = list.get((index + offset) % list.size());
                index++;
                return result;
            }
        };
    }

    public static void main(String[] args) {

        List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);

        Iterators.toStream(list.iterator())
                .filter(x -> x % 2 == 0).findFirst().ifPresent(System.out::println);
        System.out.println();

        Iterators.toStream(rotated(list, 2)).forEach(System.out::println);
        System.out.println();

        Iterators.toStream(rotated(list, 2))
                .filter(x -> x % 2 == 0).findFirst().ifPresent(System.out::println);

    }
}
